﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Data.Common;

public partial class MRP_DailyProduce : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void UIServer1_CmdFieldFire(object sender, Evolutility.UIServer.CmdFieldEventArgs e)
    {
        int id = Int32.Parse(e.PK);
        string sSQL = "";
        DateTime produceDate = DateTime.Today;
        string produceCode = "";
        int batchCount = 1, eachBatch=1;
        int quantity=0;
        int productID = 0;

        if (e.CommandText.Equals("发布"))
        {
            Database db = DatabaseFactory.CreateDatabase("MRPSqlServer");

            //生成一个序列号

            using (IDataReader reader = db.ExecuteReader(CommandType.Text,
                string.Format("Select Max(ProduceCode),produceDate from MRP_DailyProduce where produceDate=(Select DP.produceDate from MRP_DailyProduce DP where DP.ID={0}) group by produceDate", id)))
            {
                if (reader.Read())
                {
                    produceDate = DateTime.Parse(reader[1].ToString());
                    if ((String.IsNullOrEmpty(reader[0].ToString())) || (String.IsNullOrEmpty(reader[0].ToString().Split('_')[1])))
                        produceCode = string.Format("{0}_{1:D2}", produceDate.ToString("yyyyMMdd"), 1);
                    else
                    {
                        int serialID = Int32.Parse(reader[0].ToString().Split('_')[1]) + 1;
                        produceCode = string.Format("{0}_{1:D2}", produceDate.ToString("yyyyMMdd"), serialID);
                    }

                }
                else//不成功
                {
                    MRPUtility.WriteErrorLog("为日生产计划生成序号时出错了！");
                    return;
                }
            }

            using (IDataReader reader = db.ExecuteReader(CommandType.Text, string.Format("Select Batch,Quantity,ProductID from MRP_DailyProduce where ID={0}", id)))
            {
                if (reader.Read())
                {
                    eachBatch = Int32.Parse(reader["Batch"].ToString());

                    

                    quantity = Int32.Parse(reader["Quantity"].ToString());

                    if (eachBatch == 0)
                        eachBatch = quantity;
                    productID = Int32.Parse(reader["ProductID"].ToString());

                }
            }

            batchCount = (quantity % eachBatch == 0) ? quantity / eachBatch : ((quantity - quantity % eachBatch) / eachBatch) + 1;
            int remained = quantity % eachBatch;
            //eachBatch = (quantity - remained) / batchCount;

            if (remained == 0)
                remained = eachBatch;

            using (DbConnection connection = db.CreateConnection())
            {
                connection.Open();
                DbTransaction transaction = connection.BeginTransaction();

                try
                {
                    for (int i = 1; i <= batchCount; i++)
                    {
                        if (i == batchCount)
                            eachBatch = remained;

                        sSQL = string.Format("INSERT INTO [MRP_DailyProduceBatch]([DailyProduceID],[BatchCode],[PQuantity])VALUES({0},'{1}_{2:D2}',{3})",
                            id, produceCode, i, eachBatch);
                        db.ExecuteNonQuery(transaction,CommandType.Text, sSQL);


                    }

                    sSQL = string.Format("Update MRP_DailyProduce set [status]=2,[PublishDate]=CONVERT(date,SYSDATETIME()),[ProduceCode]='{1}' where ID={0}", id, produceCode);
                    db.ExecuteNonQuery(transaction,CommandType.Text, sSQL);

                    //增加产品在途库存
                    if (productID > 0)
                    {
                        sSQL = string.Format("Update dbo.MRP_Stock set InTransit=InTransit+{1} where MRP_Stock.MaterialID = {0};", productID, quantity);
                        
                        db.ExecuteNonQuery(transaction, CommandType.Text, sSQL);
                    }
                    // Commit the transaction.
                    transaction.Commit();
                    //transaction.Rollback();

                }
                catch
                {
                    // Roll back the transaction. 
                    transaction.Rollback();
                }
                connection.Close();

            }

            

        }


    }
}
